
export declare interface ICookie {
    getCookie: (name: string) => string | null
    setCookie: (name: string, value: string, options?: ICookieOptions) => void
    delCookie: (name: string, options?: ICookieOptions) => void
}
export declare interface ICookieOptions {
    expires?: number | Date, // 过期时间（单位：秒）
    path?: string,
    domain?: string,
    secure?: boolean,
    sameSite?: 'strict' | 'lax' | 'none'
}

export const useCookie = () => {
    const defaultOptions = {
        expires: 1 * 24 * 60 * 60, // 默认保存一天，若未设置值，则为会话期间
        path: '',   // 默认在当前页面所在的路径下可用，若设置'/store'则表示在store页面及其子路径下可用
        domain: '', //默认情况下，cookie 仅在创建它的域中可用。例如，如果将 cookie 的域设置为 `example.com`，则可以在 `www.example.com` 和 `store.example.com` 中访问该 cookie。
        secure: false, // true:只能通过HTTPS连接传输，false：HTTP和HTTPS都可。
        sameSite: 'none', // 用于防止跨站点请求伪造。
    }
    const cookieFns: ICookie = {
        getCookie: (name) => {
            let cookies = document.cookie.split(';');
            let cookie = cookies.find(c => c.trim().startsWith(name + '='))
            return cookie ? decodeURIComponent(cookie.split('=')[1]) : null;
        },
        setCookie: (name, value, options = {}) => {
            Object.assign(options, defaultOptions);
            let cookie = `${name}=${encodeURIComponent(value)}`;
            if (options?.expires instanceof Date) {
                cookie += `;expires=${options.expires.toUTCString()}`;
            } else if (typeof options.expires === 'number') {
                const expires = new Date();
                expires.setTime(expires.getTime() + options.expires * 1000);
                cookie += `;expires=${expires.toUTCString()}`;
            }
            options?.path && (cookie += `;path=${options?.path}`);
            options?.domain && (cookie += `;domain=${options?.domain}`);
            options?.secure && (cookie += `;secure`);
            document.cookie = cookie;
        },
        delCookie: (name, options) => {
            cookieFns.setCookie(name, '', { expires: new Date(0), ...options });
        }
    }
    return cookieFns;
}